package com.example.practice2023.service;

import com.example.practice2023.mapper.ArticleMapper;
import com.example.practice2023.pojo.Article;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleService {

    @Resource
    private ArticleMapper articleMapper;

    public Map<String, Object> selectByPage(int page, int limit,Article article) {
        int index = (page - 1) * limit;   // 通用性的分页起始下标计算
        List<Article> articleList = articleMapper.selectByPage(index, limit,
                article.getArticle_title(),
                article.getArticle_status());
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count",articleMapper.selectAllCount(article.getArticle_title(), article.getArticle_status()));   // 通过数据库全查功能，把所有的记录个数统计出来
        map.put("data", articleList);
        return map;
    }
    public Map<String, Object> insert(Article article) {
        Map<String, Object> map = new HashMap<>();
//        String password = article.getPassword();
//         这里手动加密5次 MD5
//        String md5Pass = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
//        md5Pass = DigestUtils.md5DigestAsHex(md5Pass.getBytes(StandardCharsets.UTF_8));
//        md5Pass = DigestUtils.md5DigestAsHex(md5Pass.getBytes(StandardCharsets.UTF_8));
//        md5Pass = DigestUtils.md5DigestAsHex(md5Pass.getBytes(StandardCharsets.UTF_8));
//        md5Pass = DigestUtils.md5DigestAsHex(md5Pass.getBytes(StandardCharsets.UTF_8));
//        user.setPassword(md5Pass);
//        user.setRegisterTime(new Timestamp(System.currentTimeMillis()));  // util Date  sql Date  Time  Timestamp
        articleMapper.insert(article);
        map.put("code", 200);
        map.put("msg", "新增文章成功");
        map.put("data", article);
        return map;
    }

    public Map<String, Object> deleteById(Integer article_ID) {
        Map<String, Object> map = new HashMap<>();
        articleMapper.deleteById(article_ID);
        map.put("code", 200);
        map.put("msg", "删除文章成功");
        map.put("id", article_ID);
        return map;
    }

    public Map<String, Object> updateById(Article article) {
        Map<String, Object> map = new HashMap<>();
        articleMapper.updateById(article);
        map.put("code", 200);
        map.put("msg", "更新文章成功");
        map.put("data", article);
        return map;
    }

    public Map<String, Object> setStatus(Article article) {
        Map<String, Object> map = new HashMap<>();
        articleMapper.setStatus(article);
        map.put("code", 200);
        map.put("msg", "成功");
        map.put("data", article);
        return map;
    }

}
